<?php
class UsersController extends AppController {
	public $name = 'Users';
	var $components = array(
		'Attachment' => array(
			'files_dir' => 'avatars',
			'rm_tmp_file' => false,
			'max_file_size' => 2097152, /* in bytes */
			'images_size' => array(
				'large' => array(78, 78, 'resizeCrop'),
				'small' => array(25, 25, 'resizeCrop')
			),
			'allow_non_image_files' => false
		)
	);

	function beforeFilter() {
		$this->Auth->allow('login', 'register', 'forgotPassword', 'resetPassword', 'profile', 'unlock');
		$this->Auth->Authorize = 'controller';
		$this->Security->blackHoleCallback = 'blackhole';
	}

/* Don't blackhole ajax requests made for login for and the admin links */
	function blackhole($type) {
		if(($this->request->params['action'] == 'login' && $this->request->is('ajax')) || ($this->request->params['action'] == "adminLinks" && $this->request->is('ajax'))){
			return true;
		}
		throw new MethodNotAllowedException(__('Nope: ' . $type . ' - ' . Router::url($this->here, true)));
	}

	public function isAuthorized($user) {
		if (in_array(strtolower($this->action), array('add', 'edit', 'delete', 'index', 'adminlinks'))) {
			return (AuthComponent::User('role') == '3') ? true : false;
		}
		return true;
	}

	public function index(){
		$this->paginate = array(
			'order' => array('User.created'),
			'limit' => 10
		);
		$users = $this->paginate('User');
		$this->set('users', $users);
	}

	public function login(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Login');
		if($this->request->is('post') || $this->request->is('ajax')){
			$this->User->recursive = -1;
			$submittedUser = $this->User->find('all', array(
					'fields' => array('User.username', 'User.id', 'User.logintries', 'User.email'),
					'conditions' => array(
					'username' => $this->request->data[$this->User->alias]['username']
			)));

			if(isset($submittedUser[0][$this->User->alias]['id'])){
				/* Account exists */
				if(isset($submittedUser[0][$this->User->alias]['logintries']) && $submittedUser[0][$this->User->alias]['logintries'] <= 4 ){
					/* Account is not locked yet, proceed to try login*/
					if($this->Auth->login()){
						/* Login accepted, reset logintries */
						$this->User->id = $this->Auth->User('id');
						$this->User->saveField('logintries', 0);

						if($this->request->is('ajax')){
							$this->autoRender = false;
							$status = array('status' => 'success');
							return json_encode($status);
						}
						$this->redirect($this->Auth->redirect());
					}else{
						/* Invalid login, increment logintries on submitted account */
						if(isset($submittedUser[0][$this->User->alias]['id'])){
							$this->User->updateAll(array('User.logintries' =>'User.logintries + 1'), array('User.id' => $submittedUser[0][$this->User->alias]['id']));;
						}

						if($this->request->is('ajax')){
							$this->autoRender = false;
							$status = array('status' => 'no dice');
							return json_encode($status);
						}
					}
				}else{
					/* Account is now locked, update account with lockcode uuid and send an email to account owner */
					$lockcode = String::uuid();

					$this->User->id = $submittedUser[0][$this->User->alias]['id'];
					$this->User->saveField('lockcode', $lockcode);

					$email = new CakeEmail();
					$email->config('noreply');
					$email->template('account_locked');
					$email->viewVars(array('userData' => $submittedUser[0], 'lockcode' => $lockcode, 'userIP' => $_SERVER['REMOTE_ADDR']));
					$email->to($submittedUser[0][$this->User->alias]['email']);
					$email->subject(SITE_NAME . ' Account Locked');
					$email->emailFormat('html');

					$email->send();

					if($this->request->is('ajax')){
						$this->autoRender = false;
						$status = array('status' => 'locked');
						return json_encode($status);
					}

					$this->Session->setFlash('This account has now been locked. An email has been sent to the account owner.', 'default', array('class' => 'nodice'));
				}
			}else{
				/* Account doesn't exist */
			}
		}
	}

/* Make sure $user_id && $lockcode have been set
 * If user exists make sure lock code is valid, if so then redirect
 */
	public function unlock($user_id = null, $lockcode = null){
		if(isset($user_id) && isset($lockcode)){
			$this->User->id = $user_id;
			if($this->User->exists()){
				if($this->User->unlock($lockcode)){
					$this->Session->setFlash('Your account has been unlocked. Please login', 'default', array('class' => 'success'));
				}
			}
		}
		$this->redirect(array('controller' => 'threads', 'action' => 'home'));
	}

	public function register(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Register an account');
		if($this->request->is('post') || $this->request->is('put')){
			$this->User->create();
			if($this->User->Save($this->request->data)){
				$this->User->sendWelcomeMessage();
				$this->data[$this->alias]['id'] = $this->id;
				$this->data[$this->alias]['password'] = $this->data[$this->alias]['password1'];
				// automatically log user in
				if($this->Auth->login()){
					$this->Session->setFlash('Your account has been created', 'default', array('class' => 'success'));
					$this->redirect(array('controller' => 'forums', 'action' => 'displayForums'));;
				}
			}
		}
	}

	public function history(){

	}

	public function profile($username = null){
		$userData = $this->User->find('first',	array(
			'conditions' => array(
				'username' => $username
			)
		));
		if(!isset($userData['User']['id'])){
			throw new NotFoundException('User not found');
		}

		$this->User->Thread->recursive = 0;
		$oldThreads = $this->Thread->find('all', array(
			'order' => 'Thread.created DESC',
			'conditions' => array(
				'OR' => array(
					'Thread.home' => 1,
					'AND' => array(
						'Thread.thread_id' => 0,
						'Thread.sub_forum_id' => 1
		)))));


		$years = array();
		foreach($oldThreads as $thread){
			$year = substr($thread['Thread']['created'], 0, 4);
			$oldThreads2[$year][] = $thread;
		}

		$this->set('userData', $userData);
		$this->set('latestUserThreads', $userData['Thread']);
		$this->set('roles', array(1 => 'Member', 2 => 'Moderator', 3 => 'Admin'));
		$this->set('title_for_layout', SITE_NAME . ' &bull; Profile &bull; ' . $userData['User']['username']);
		$this->set('years', $years);
		$this->set('oldThreads', $oldThreads2);
	}

	public function add(){
		if($this->request->is('post') || $this->request->is('put')){
			$this->User->create();
			if($this->User->Save($this->request->data)){
				$this->Session->setFlash('User created', 'default', array('class' => 'success'));
				$this->redirect(array('controller' => 'users', 'action' => 'index'));
			}
		}
	}

	public function account(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Account Information');
		$this->User->id = $this->Auth->User('id');
			if($this->request->is('get')){
				$this->request->data = $this->User->read();
				unset($this->request->data[$this->User->alias]['password']);
			}else{
				// password
				if(empty($this->request->data[$this->User->alias]['password1']) && empty($this->request->data[$this->User->alias]['password2'])){
					unset($this->request->data[$this->User->alias]['password'], $this->request->data[$this->User->alias]['password1'], $this->request->data[$this->User->alias]['password2']);
				}

				// avatar
				if($this->Attachment->upload($this->request->data[$this->User->alias])){
					$this->Session->write('Auth.User.user_content_type', $this->request->data[$this->User->alias]['user_content_type']);
					$this->Session->write('Auth.User.user_file_size', $this->request->data[$this->User->alias]['user_file_size']);
					$this->Session->write('Auth.User.user_file_name', $this->request->data[$this->User->alias]['user_file_name']);
					$this->Session->write('Auth.User.user_file_path', $this->request->data[$this->User->alias]['user_file_path']);
				};

				if($this->User->save($this->request->data)){
					$this->Session->write('Auth.User.email', $this->request->data[$this->User->alias]['email']);
					$this->Session->setFlash('Account updated', 'default', array('class' => 'success'));
					$this->redirect(array('controller' => 'users', 'action' => 'account'));
				}
			}

		}

	public function edit($id = null){
		$this->User->id = $id;
		if(!$this->User->exists()){
			throw new NotFoundException('User not found');
		}

		if($this->request->is('get')){
			$this->request->data = $this->User->read();

		}else{
			if($this->User->updateAccount($this->request->data)){
				$this->Session->setFlash('Account updated', 'default', array('class' => 'success'));
				$this->redirect(array('controller' => 'users', 'action' => 'index'));
			}
		}
	}

	public function adminLinks(){
		$this->autoRender = false;
		$data = $this->render(DS . 'Elements' . DS . 'admin_links', false);
		return $data;
	}

	public function resetPassword($id = null, $token = null){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Reset password');
		$this->User->id = $id;
		if($this->User->exists()){
			$userData = $this->User->read();
			if($userData['User']['token'] == $token && $token !== null){
				$this->set('username', $userData['User']['username']);
				if($this->request->is('post')){
					$this->User->set($this->request->data);
					if($this->User->savePassword()){
						$this->Session->setFlash('Your password has been updated. Please login', 'default', array('class' => 'success'));
						$this->redirect(array('controller' => 'threads', 'action' => 'home'));
					}
				}
			}else{
				$this->redirect(array('controller' => 'threads', 'action' => 'home'));
			}
		}else{
			$this->redirect(array('controller' => 'threads', 'action' => 'home'));
		}
	}

	public function forgotPassword(){
		$this->set('title_for_layout', SITE_NAME . ' &bull; Forgot password');
		if($this->request->is('get')){

		}
		if($this->request->is('post')){
			$this->User->recursive = -1;
			$userData = $this->User->find('first', array('conditions' => array('username' => $this->request->data[$this->User->alias]['forgotusername'])));
			$this->User->set($this->request->data);
			if(count($userData) > 0){
				$token = String::uuid();
				$this->User->id = $userData['User']['id'];
				if($this->User->saveField('token', $token)){

					$email = new CakeEmail();
					$email->config('noreply');
					$email->template('reset_password');
					$email->viewVars(array('userData' => $userData, 'token' => $token, 'userIP' => $_SERVER['REMOTE_ADDR']));
					$email->to($userData['User']['email']);
					$email->subject(SITE_NAME . ' Password Recovery');
					$email->emailFormat('html');

					$email->send();

					$this->Session->SetFlash('An email has been sent with further instructions on how to reset your password', 'default', array('class' => 'success'));
					$this->redirect(array('controller' => 'threads', 'action' => 'home'));
				}
			}

		}
		$this->render('forgot_password');
	}

	public function logout(){
		$this->redirect($this->Auth->logout());
	}


	public function delete(){
		if($this->request->is('get')){
			throw new MethodNotAllowedException();
		}elseif($this->request->is('post')){
			$i = 0;
			foreach($this->request->data['Forum']['selectedForums'] AS $forumId){
				// delete forum
				$this->Forum->id = $forumId;
				$this->Forum->delete();
				$i++;
			}
			$this->Session->setFlash($i . ': Forums have been deleted.', 'default', array('class' => 'success'));
			$this->redirect(array('action' => 'index'));
		}
	}
}


